import styles from './index.less';
import classNames from 'classnames';
import { useEffect, useState } from 'react';
import { CopyToClipboard } from 'react-copy-to-clipboard';
import { message } from 'antd';
import { history, useModel } from 'umi';
import { locationHrefAddQuerys } from '@/utils';
import { showLogin, useLoginUrl } from '@/hooks/login';
import storage from '@/utils/storage';
import { INVITED_REWARD_CLASSIDS, LDX_REWARD_DETAIL_CLASSIDS } from '@/common/const';
import { allGet } from '@/services/pc';

const Step = ({ data }) => {
  const activedIndex = data.findLastIndex((item) => item.username);
  const col = data.length > 4 ? 4 : data.length;
  const width = 100 / col + '%';
  return (
    <div className={styles.step}>
      <div className={styles.wraper}>
        {data.map((item, index) => {
          const actived = index <= activedIndex;
          return (
            <div
              key={item.id}
              className={classNames(styles.item, { [styles.actived]: actived })}
              style={{ width }}
            >
              <div className={styles.index}>
                <div className={styles.avatar} style={{ backgroundImage: `url(${item.avatar})` }}>
                  {actived ? '' : index + 1}
                </div>
              </div>
              <i className={styles.line} />
              <div className={styles.momey}>
                <span className={styles.unit}></span> {item.reward}
                <i className={styles.icon} />
              </div>
              <div className={styles.yqindex}>邀请第{index + 1}位</div>
              {actived && (
                <div className={styles.tx} onClick={() => history.push('/account')}>
                  已到账户中心
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
};

const RewardDetail = ({ onClose, data, classDetail }) => {
  const { userInfo } = useModel('user');
  const stepData = data?.list?.map((item, index) => ({ id: index, ...item })) || [];
  // const [shareCode, setShareCode] = useState('')
  // useEffect(() => {
  //   const url = locationHrefAddQuerys({ fromuid: userInfo.uid })
  //   setShareCode(url)
  // }, [])
  const code = 1111;

  const copyUrl = () => {
    if (!userInfo.uid) {
      return showLogin({});
    }
    const url = locationHrefAddQuerys({ fromuid: userInfo.uid });
    const input = document.createElement('textarea');
    input.setAttribute('id', '__mouse__position_input');
    input.style.transform = 'translateY(-999999999px)';

    let content = `
${url}
分享人：${userInfo.username || ''}`;

    // 只有当 data?.reduce 大于 0 时才添加优惠额度行
    if (data?.reduce > 0) {
      content += `
优惠额度：${data.reduce}元`;
    }

    // 其他字段正常显示
    content += `
优惠课程：《${classDetail.name}》
邀请码：${data.code}（付款的时候输入使用）
`;

    input.value = content;
    document.body.appendChild(input);
    input.select();
    document.execCommand('copy');
    document.body.removeChild(input);
    message.success('复制成功');
  };
  return (
    <>
      <i className={styles.mask} onClick={onClose} />
      <div className={styles.rewardInfo}>
        <i className={styles.close} onClick={onClose} />
        <div className={styles.main}>
          <i className={styles.header} />
          <div className={styles.body}>
            <img
              loading="lazy"
              className={styles.title}
              src={require('./images/title.png')}
              alt=""
            />
            <div className={styles.des}>
              {data?.reduce > 0 ? `受邀同学亦可优惠${data?.reduce}元` : ''}
            </div>
            <Step data={stepData} />
            <div className={styles.tips}>
              <i className={styles.icon} />
              您有一笔现金还未领取，邀请成功并购买即可领取
            </div>
          </div>
          <i className={styles.rmb1} />
          <i className={styles.rmb2} />
          <i className={styles.rmb3} />
          <i className={styles.fz} onClick={copyUrl} />
          {/* <CopyToClipboard text={shareCode} onCopy={() => message.success('复制成功~')}>
          <i className={styles.fz} />
        </CopyToClipboard> */}
        </div>
      </div>
    </>
  );
};

interface IndexProps {
  className?: string;
  data: any;
  classDetail: any;
}
const Index: React.FC<IndexProps> = ({ className, data, classDetail }) => {
  const [visible, setVisible] = useState(false);
  const handleClick = () => {
    setVisible(true);
  };
  const handleClose = () => {
    setVisible(false);
    const storageData = storage.get(LDX_REWARD_DETAIL_CLASSIDS);
    storage.set(LDX_REWARD_DETAIL_CLASSIDS, { ...storageData, [classDetail.classid]: true });
  };
  useEffect(() => {
    // 如果为1则自动弹出老带新活动窗口, 并且不是第一次
    const storageData = storage.get(LDX_REWARD_DETAIL_CLASSIDS);
    if (data.notice == 1 && !storageData[classDetail.classid]) {
      setVisible(true);
    }
  }, [data]);
  return (
    <>
      <div className={classNames(styles.reward, className)} onClick={handleClick}>
        <span className={styles.text}>
          <span className={styles.unit}></span>
          {data?.cashbacks}
        </span>
      </div>
      {visible && <RewardDetail onClose={handleClose} data={data} classDetail={classDetail} />}
    </>
  );
};

export const RewardSuccess = ({ onClose, visible, reduce, name, code, people, reward }) => {
  const { userInfo } = useModel('user');
  useEffect(() => {
    // const url = locationHrefAddQuerys({ fromuid: userInfo.uid })
    // setShareCode()
  }, []);
  const copyUrl = () => {
    const url = locationHrefAddQuerys({ fromuid: userInfo.uid });
    const input = document.createElement('textarea');
    input.setAttribute('id', '__mouse__position_input');
    input.style.transform = 'translateY(-999999999px)';
    input.value = `
    ${url}
    分享人：${userInfo.username}
    优惠额度：${reduce}元
    优惠课程：《${name}》
    邀请码：${code}（付款的时候输入使用）
    `;
    document.body.appendChild(input);
    input.select();
    document.execCommand('copy');
    document.body.removeChild(input);
    message.success('复制成功');
  };

  return (
    <>
      {visible && (
        <>
          {' '}
          <i className={styles.mask} onClick={onClose} />
          <div className={styles.rewardSuccess}>
            <i className={styles.close} onClick={onClose} />
            <div className={styles.main}>
              <div className={styles.title}>
                成功邀请第<span className={styles.num}>{people}</span>位同学
              </div>
              <div className={styles.tips}>奖励</div>
              <div className={styles.money}>
                <span className={styles.text}>
                  {reward}
                  <span className={styles.unit}>¥</span>
                </span>
              </div>
              <i className={styles.fz} onClick={copyUrl} />
              {/* <CopyToClipboard text={shareCode} onCopy={() => message.success('复制成功~')}>
            <i className={styles.fz} />
          </CopyToClipboard> */}
            </div>
          </div>
        </>
      )}
    </>
  );
};

// 拉新优惠
export const InvitedReward = ({ onClose, visible, num, classId, fromuid }) => {
  const { userInfo } = useModel('user');
  const loginUrl = useLoginUrl();
  const handleClick = async () => {
    if (userInfo.uid) {
      const response = await allGet({
        params: {
          mod: 'coupon',
          do: 'receive',
          classid: classId,
          fromuid: fromuid,
          version: 'pc1.0',
        },
      });
      if (response.success) {
        message.success('领取成功');
        const data = storage.get(INVITED_REWARD_CLASSIDS);
        storage.set(INVITED_REWARD_CLASSIDS, { ...data, [classId]: true });
        onClose();
      }
    } else {
      window.location.href = loginUrl;
    }
  };
  return (
    <>
      {visible && num > 0 && (
        <>
          {' '}
          <i className={styles.mask} onClick={onClose} />
          <div className={styles.invitedReward}>
            <i className={styles.close} onClick={onClose} />
            <div className={styles.main}>
              <div className={styles.num}>{num}</div>
              <i className={styles.line} />
              <div className={styles.title}>
                <div className={styles.img} />
                <div className={styles.subtitle}>拉新优惠</div>
              </div>
              <div className={styles.button} onClick={handleClick}></div>
            </div>
          </div>
        </>
      )}
    </>
  );
};
export default Index;
